import { createDatabase, Database } from "db0";
import sqliteConnector from "db0/connectors/better-sqlite3";
import { APP_DATABASE_PATH } from "~/global/constant";
import { createStorage } from "unstorage";
import db0Driver from "unstorage/drivers/db0";

export const db: Database = createDatabase(
  sqliteConnector({
    path: APP_DATABASE_PATH
  })
);

export const kv = createStorage({
  driver: db0Driver({
    database: db
  })
});

export const beginTransactional = async <T>(callback: () => Promise<T>): Promise<T> => {
  try {
    db.sql`BEGIN`;
    const r = await callback();
    db.sql`COMMIT`;
    return r;
  } catch (e) {
    db.sql`ROLLBACK`;
    console.error(e);
    return Promise.reject(e);
  }
};
